import tushare as ts
import pandas as pd
import sqlite3
import time
dbpath='/home/xzh/data/stockdata2018.db'
conn = sqlite3.connect(dbpath) #
#df = ts.get_tick_data('600581',date='2015-01-09')
#timedelta_range(start='1 days', periods=5, freq='D') timedelta_range(start='1 days', end='2 days', freq='30T')
#pd.period_range('201001','201005',freq='M')
#pd.TimedeltaIndex(['1 days', '1 days, 00:00:05', np.timedelta64(2,'D'), np.timedelta(days=2,seconds=2)])
def save_data(stock_code,date,src='sn'):
    try:
         detail = ts.get_tick_data(stock_code,date=str(date),src=src)
         time.sleep(1)
         if detail is   None  :
             print(str(date)+'日无数据')
         else:
             detail['oper_dt']=date
             detail['stock_code']=stock_code
             detail .to_sql('tp_stock',conn,if_exists='append')
             print(str(date))
    except Exception as e:
        print(str(e))
        time.sleep(2)
        save_data(stock_code,date,src)
        
def get_by_code_dt(stock_code,start,end,src='tt'): # tt sn nt
    conn.execute("drop table if exists tp_stock")
    sql="""SELECT date  
            FROM stocks where code='{0}'  and date between '{1}' and '{2}'
            group by  date""".format(stock_code,start,end)
    dts=pd.read_sql(sql,conn)
    if dts.shape[0]>1:
        for i in dts.index:
            save_data(stock_code,str(dts.loc[i,'date']),src)
    else:
        for date in pd.period_range(start,end,freq='D'):
            save_data(stock_code,str(date),src)
 
if __name__ =='__main__':
    stockcode='600696'
    date='2019-02-01'
    get_by_code_dt('600696','2019-01-01','2019-02-01','tt') 
 